<!--
 * @Description: 我要报修
 * @Author: Ronda
 * @Date: 2022-02-16 09:30:08
 * @LastEditors: Ronda
 * @LastEditTime: 2022-05-23 15:13:16
-->
<template>
  <div class="repair-order-container">
    <el-form
      ref="repairForm"
      :model="repairForm"
      :rules="rules"
      label-width="0"
      @submit.native.prevent="toSubmit"
    >
      <el-form-item>
        <div class="form-label">工程设备</div>
        <div class="block full-width">
          <!--级联选择器 数据源为equipmentOptions，包含工程和设备的层级关系  添加了@change事件处理选择变化-->
          <el-cascader
            v-model="repairForm.device_path"
            :options="equipmentOptions"
            :props="{ expandTrigger: 'hover' }"
            @change="handleEquipmentChange"
            placeholder="请选择需要报修的设备"
            class="full-width-cascader"
          >
          </el-cascader>
        </div>
      </el-form-item>

      <el-form-item prop="bill_why">
        <div class="form-label">报修原因</div>
        <!--使用el-input的textarea类型   设置多行文本输入框-->
        <el-input
          type="textarea"
          :rows="5"
          placeholder="请描述设备故障现象或需要维修的原因"
          v-model="repairForm.bill_why"
          class="full-width-input"
        >
        </el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" native-type="submit" :loading="submitting">
          提交
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { post } from "@/utils/request";
import { getToken } from "@/utils/auth";

export default {
  name: "RepairOrder",
  //repairForm: 存储表单数据（设备路径和报修原因）
  //rules: 表单验证规则
  //submitting: 提交状态标志
  //equipmentOptions: 级联选择器的选项数据，包含工程和设备信息
  data() {
    return {
      repairForm: {
        device_path: [],
        bill_why: "",
      },
      rules: {
        device_path: [
          {
            required: true,
            message: "请选择需要报修的设备",
            trigger: "change",
          },
        ],
        bill_why: [
          { required: true, message: "请输入报修原因", trigger: "blur" },
        ],
      },
      submitting: false,
      equipmentOptions: [
        {
          value: "shanxi-nongda",
          label: "山西农大主体育场工程",
          children: [
            {
              value: "shanxi-nongda-stadium",
              label: "三号设备",
              device_id: 3, // 添加设备ID
              engineer_id: 1, // 假设工程师ID
            },
          ],
        },
        {
          value: "tyut",
          label: "太原理工大学一号教学楼工程",
          children: [
            {
              value: "tyut-teaching-building1",
              label: "一号设备",
              device_id: 1,
              engineer_id: 2,
            },
            {
              value: "tyut-teaching-building2",
              label: "二号设备",
              device_id: 2,
              engineer_id: 2,
            },
          ],
        },
        {
          value: "north-china-university",
          label: "中北大学",
          children: [
            {
              value: "north-china-university-device",
              label: "六号设备",
              device_id: 6,
              engineer_id: 3,
            },
          ],
        },
        {
          value: "lanzhou-university-technology",
          label: "兰州理工大学",
          children: [
            {
              value: "lanzhou-university-technology-device1",
              label: "四号设备",
              device_id: 4,
              engineer_id: 4,
            },
            {
              value: "lanzhou-university-technology-device2",
              label: "五号设备",
              device_id: 5,
              engineer_id: 4,
            },
          ],
        },
        {
          value: "yancheng-normal-university",
          label: "盐城师范学院通榆校区",
          children: [],
        },
      ],
    };
  },
  methods: {
    handleEquipmentChange(value) {
      // 处理设备选择变化，保存选中的设备信息
      if (value && value.length === 2) {
        const [projectValue, deviceValue] = value;
        const selectedProject = this.equipmentOptions.find(
          (item) => item.value === projectValue
        );
        if (selectedProject) {
          const selectedDevice = selectedProject.children.find(
            (item) => item.value === deviceValue
          );
          if (selectedDevice) {
            this.selectedDeviceInfo = selectedDevice;
          }
        }
      }
    },
    async toSubmit() {
      try {
        // 验证表单
        const valid = await this.$refs.repairForm.validate();
        if (!valid) return;

        if (!this.selectedDeviceInfo) {
          this.$message.error("请选择有效的设备");
          return;
        }

        this.submitting = true;

        // 准备请求数据
        const requestData = {
          engineer_id: this.selectedDeviceInfo.engineer_id, // 工程师ID
          device_id: this.selectedDeviceInfo.device_id, // 设备ID
          account_id: this.getCurrentAccountId(), // 账户ID
          bill_why: this.repairForm.bill_why, // 报修原因
        };

        // 调用接口
        const response = await post("/workorder/repairOrder", requestData);

        // 处理成功响应
        this.$message.success("报修成功");
        this.$refs.repairForm.resetFields();
        this.$router.push("/am/order/list");
      } catch (error) {
        console.error("提交错误:", error);
        let errorMessage = "报修失败";

        if (error.response) {
          // 服务器返回了错误状态码
          errorMessage = error.response.data.message || errorMessage;
        } else if (error.message) {
          // 其他错误
          errorMessage = error.message;
        }

        this.$message.error(errorMessage);
      } finally {
        this.submitting = false;
      }
    },
    getCurrentAccountId() {
      // 从token或其他地方获取当前账户ID
      // 这里假设token中包含用户信息，实际应根据您的项目实现
      const token = getToken();
      if (token) {
        try {
          const decoded = JSON.parse(atob(token.split(".")[1]));
          return decoded.account_id || decoded.id || 1; // 默认返回1
        } catch (e) {
          console.error("解析token失败:", e);
          return 1; // 默认返回1
        }
      }
      return 1; // 默认返回1
    },
  },
};
</script>

<style lang="scss" scoped>
.repair-container {
  padding: 20px;
}
</style>
